﻿using System;
using BaseRepository.Cache;
using Castle.DynamicProxy;
using Extensions.Interceptor.Cache.Keys;

namespace Extensions.Interceptor.Cache;

public sealed class MemoryCacheInterceptor : BaseCacheInterceptor
{
    private readonly ICacheRepository _cacheRepository;

    public MemoryCacheInterceptor(ICacheRepository cacheRepository,KeyContext keyContext) : base(keyContext)
    {
        _cacheRepository = cacheRepository??throw new ArgumentNullException(nameof(cacheRepository));
    }

    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <param name="key"></param>
    /// <param name="invocation"></param>
    /// <returns></returns>
    protected override bool Get(string key, IInvocation invocation)
    {
        var isExist =  _cacheRepository.TryGetValue(key, out var value);
        if (isExist)
        {
            invocation.ReturnValue = value;
        }
        return isExist;
    }
    /// <summary>
    /// 删除缓存
    /// </summary>
    /// <param name="key"></param>
    protected override void Delete(string key)
    {
        _cacheRepository.Remove(key);
    }
    /// <summary>
    /// 设置缓存
    /// </summary>
    /// <param name="key"></param>
    /// <param name="invocation"></param>
    protected override void Set(string key, IInvocation invocation)
    {
        // 如果是null 也会保存  这是可以的
       _cacheRepository.Set(key,invocation.ReturnValue);
    }

   
}